from django.urls import reverse

from django.contrib import messages
from django.contrib.auth import login, authenticate, logout
from django.http import HttpResponse
# from django.shortcuts import render
from django.shortcuts import render, redirect
from django.views import View
import re

from pymysql import DatabaseError
from django.contrib.auth.mixins import LoginRequiredMixin
from apps.index.models import User

# Create your views here.
from apps.user.models import Article


class LoginView(View):
    def get(self, request):
        return render(request, 'sign-in.html')

    def post(self, request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        cc = request.POST.get('cc')

        email_zhuce = request.POST.get('email_zhuce')
        username_zhuce = request.POST.get('username_zhuce')
        password_zhuce = request.POST.get('password_zhuce')
        password2_zhuce = request.POST.get('password2_zhuce')
        name_zhuce = request.POST.get('name_zhuce')
        # 登陆
        if all([username, password]):
            if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
                messages.success(request, "请输入5-20个字符的用户名")
                return render(request, 'sign-in.html')
            if not re.match(r'^[0-9A-Za-z]{8,20}$', password):
                messages.success(request, "请输入8-20个字符的密码")
                return render(request, 'sign-in.html')
            user = authenticate(username=username, password=password)
            if user is None:
                messages.success(request, "用户名密码输入错误")
                return render(request, 'sign-in.html')
            login(request, user)
            # 设置状态保持的周期
            if cc != 'on':
                # 没有记住用户：浏览器会话结束就过期
                request.session.set_expiry(0)
            else:
                # 记住用户：None表示两周后过期
                request.session.set_expiry(None)
            next = request.GET.get('next')
            if next:
                response = redirect(next)
            else:
                response = redirect(reverse('index:index'))
                # 注册时用户名写入到cookie，有效期15天
            response.set_cookie('username', user.username, max_age=3600 * 24 * 15)

            return response
        # 注册
        elif all([email_zhuce, username_zhuce, password_zhuce, password2_zhuce]):
            if not re.match(r'^[0-9a-zA-Z_]{0,19}@[0-9a-zA-Z]{1,13}\.[com,cn,net]{1,3}$',email_zhuce):
                messages.success(request, "请输入正确的邮箱")
                return render(request, 'sign-in.html')
            if not re.match(r'^[a-zA-Z0-9_]{5,20}$', username_zhuce):
                messages.success(request, "请输入5-20个字符的用户名")
                return render(request, 'sign-in.html')
            if not re.match(r'^[0-9A-Za-z]{8,20}$', password_zhuce):
                messages.success(request, "请输入8-20个字符的密码")
                return render(request, 'sign-in.html')
            if username_zhuce == password_zhuce:
                messages.success(request, "用户名不可与密码一致")
                return render(request, 'sign-in.html')
            if password_zhuce != password2_zhuce:
                messages.success(request, "两次输入密码不同")
                return render(request, 'sign-in.html')
            try:
                user = User.objects.create_user(username=username_zhuce, password=password_zhuce, email=email_zhuce,
                                                first_name=name_zhuce, mobile=1)
            except DatabaseError:
                messages.success(request, "注册失败")
                return render(request, 'sign-in.html')
            login(request, user)
            response = redirect(reverse('index:index'))
            return response
        else:
            messages.success(request, "请输入完整")
            return render(request, 'sign-in.html')


class LogoutView(View):
    """退出登录"""

    def get(self, request):
        """实现退出登录逻辑"""
        # 清理session

        logout(request)

        # 退出登录，重定向到登录页
        response = redirect(reverse('users:login'))

        # 退出登录时清除cookie中的username
        response.delete_cookie('username')

        return response


class User_CenterView(LoginRequiredMixin, View):
    #当前登陆用户中心
    def get(self, request):
        user = request.user.username
        other_users = User.objects.exclude(username=user)
        print(user)
        # article = Article.objects.filter(user_id=user)
        # print(article)
        context = {
            'contents': other_users,
            # 'article':article
        }
        return render(request, 'my-profile-feed.html', context)


class other_User_CenterView(LoginRequiredMixin, View):
    def get(self, request):
        user_id = request.GET.get('id')
        other_users = User.objects.filter(id=user_id)

        user_name = None

        for i in other_users:
            user_name = i.first_name
        user = request.user.username
        users = User.objects.exclude(username=user)
        context = {
            'username': user_name,
            'contents': users
        }
        return render(request, 'user-profile.html', context)